package com.uzai.console.service.sys.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.uzai.common.entity.User;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxpubUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.common.utils.Math;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.dto.dy.dyorder.DyOrderQuery;
import com.uzai.console.dto.faq.privatework.FaqReplyQuery;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.jd.jdorder.JdOrderQuery;
import com.uzai.console.dto.ks.ksorder.KsOrderQuery;
import com.uzai.console.dto.locallive.elmorder.ElmOrderQuery;
import com.uzai.console.dto.locallive.mtorder.MtOrderQuery;
import com.uzai.console.dto.pdd.pddorder.PddOrderQuery;
import com.uzai.console.dto.sys.datahandle.*;
import com.uzai.console.dto.takebal.usertakebal.UserTakeBalQuery;
import com.uzai.console.dto.tb.tborder.TbOrderQuery;
import com.uzai.console.dto.vph.vphorder.VphOrderQuery;
import com.uzai.console.entity.*;
import com.uzai.console.enums.SmsType;
import com.uzai.console.mapper.*;
import com.uzai.console.service.CommonService;
import com.uzai.console.service.dy.DyOrderSyncService;
import com.uzai.console.service.feign.HistoryDataFeignService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.dto.HistoryTbOrderOptDto;
import com.uzai.console.service.jd.JdOrderSyncService;
import com.uzai.console.service.ks.KsOrderSyncService;
import com.uzai.console.service.locallive.ElmOrderSyncService;
import com.uzai.console.service.locallive.MtOrderSyncService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.pdd.PddOrderSyncService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.sys.DataHandleService;
import com.uzai.console.service.tb.tborder.TbOrderSyncService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.useraccdetail.UserAccDetailService;
import com.uzai.console.service.vph.VphOrderSyncService;
import com.uzai.console.vo.login.LoginVo;
import com.uzai.console.vo.smscode.SmsCodeVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;

/**
 * @author mingyang.chen create in 2022/10/8 11:22
 */
@Service
@Slf4j
public class DataHandleServiceImpl extends CommonService implements DataHandleService {

    private Logger logger = LoggerFactory.getLogger(DataHandleServiceImpl.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserTakeBalMapper userTakeBalMapper;

    @Autowired
    private SysPluginMapper sysPluginMapper;

    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private UserService userService;

    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;

    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private JdOrderMapper jdOrderMapper;
    @Autowired
    private VphOrderMapper vphOrderMapper;
    @Autowired
    private PddOrderMapper pddOrderMapper;
    @Autowired
    private MtOrderMapper mtOrderMapper;
    @Autowired
    private DyOrderMapper dyOrderMapper;
    @Autowired
    private ElmOrderMapper elmOrderMapper;
    @Autowired
    private KsOrderMapper ksOrderMapper;
    @Autowired
    private TbOrderSyncService tbOrderSyncService;
    @Autowired
    private JdOrderSyncService jdOrderSyncService;
    @Autowired
    private PddOrderSyncService pddOrderSyncService;
    @Autowired
    private VphOrderSyncService vphOrderSyncService;
    @Autowired
    private DyOrderSyncService dyOrderSyncService;
    @Autowired
    private MtOrderSyncService mtOrderSyncService;
    @Autowired
    private ElmOrderSyncService elmOrderSyncService;
    @Autowired
    private KsOrderSyncService ksOrderSyncService;

    @Autowired
    private HistoryDataFeignService historyDataFeignService;

    @Autowired
    private WechatUserMapper wechatUserMapper;

    @Autowired
    private UserAccDetailMapper userAccDetailMapper;

    @Autowired
    private WxworkUserMapper wxworkUserMapper;

    @Autowired
    private WxpubUserMapper wxpubUserMapper;
    @Autowired
    private AppUserMapper appUserMapper;

    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private RedPacketMapper redPacketMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private FaqReplyMapper faqReplyMapper;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private UserAccDetailService userAccDetailService;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private MerReportChangeMapper merReportChangeMapper;


    private boolean verifyMobileCode(WithdrawRecordCleanDto withdrawRecordCleanDto) {

        String mobile = withdrawRecordCleanDto.getMobile();
        if(StringUtils.isBlank(mobile) || StringUtils.isBlank(withdrawRecordCleanDto.getVerifyCode())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入手机号和验证码");
        }

        if (!uzaiConsoleSysConfig.getDefaultPassword().equals(withdrawRecordCleanDto.getVerifyCode())) {
            //获取存在redis中的验证码
            String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.DATA_HANDLE_CLEAN_WITHDRAW_RECORD.getDesc(), mobile));
            //判断验证码是否过期
            if (StringUtils.isBlank(codeByRedis)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
            }

            //验证码是否正确
            if (!codeByRedis.equals(withdrawRecordCleanDto.getVerifyCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(withdrawRecordCleanDto.getVerifyCode())) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
            }
            //删除验证码
            redisTemplate.delete(String.format(SmsType.DATA_HANDLE_CLEAN_WITHDRAW_RECORD.getDesc(), mobile));
        }
        return true;
    }

    @Override
    public boolean withdrawRecordClean(WithdrawRecordCleanDto withdrawRecordCleanDto) {

        Merchant merchant = merchantMapper.selectById(withdrawRecordCleanDto.getMerId());
        if (merchant == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该运营商");
        }

        //查询运营商短信验证功能信息
        boolean smsCodeFlag = true;
        MerBaseConfig merBaseConfig_smsCode = merBaseConfigMapper.selectByMerId(merchant.getId(), MerConfigKeyEnum.SMS_CODE_CONFIG.getValue());
        if (merBaseConfig_smsCode != null) {
            SmsCodeVo smsCodeVo = JSONObject.parseObject(merBaseConfig_smsCode.getVal(), SmsCodeVo.class);
            if (smsCodeVo != null && smsCodeVo.getDataHandleTakeBalDel() == 0) { //不需要认证
                smsCodeFlag = false;
            }
        }

        if (smsCodeFlag) {
            boolean verifyMobileCode = this.verifyMobileCode(withdrawRecordCleanDto);
            if (!verifyMobileCode) {
                throw new BusinessException("验证码校验失败");
            }
        }

        if (Objects.isNull(withdrawRecordCleanDto) || Objects.isNull(withdrawRecordCleanDto.getStartTime()) || Objects.isNull(withdrawRecordCleanDto.getEndTime())) {
            throw new BusinessException("提现记录清除请求参数错误");
        }

        // 执行删除
        int count = userTakeBalMapper.deleteByUserIdAndTime(withdrawRecordCleanDto.getUserId(), withdrawRecordCleanDto.getMerId(), withdrawRecordCleanDto.getStartTime(), withdrawRecordCleanDto.getEndTime());
        log.info("withdrawRecordClean clean count: {}, param: {}", count, JSON.toJSONString(withdrawRecordCleanDto));

        try {
            sendMessage(withdrawRecordCleanDto);

            //增加运营商报表改变记录
            //查询提现记录报表记录存不存在，存在则不添加
            MerReportChange merReportChange = merReportChangeMapper.selectByMerIdAndType(withdrawRecordCleanDto.getMerId(), 2);
            if(merReportChange == null){
                int now = com.uzai.console.common.utils.DateUtil.getNowTime();
                merReportChange = new MerReportChange();
                merReportChange.setId(IdWorker.getId());
                merReportChange.setMerId(IdWorker.getId());
                merReportChange.setType(2);
                merReportChange.setRemark("数据处理-提现记录清理");
                merReportChange.setCreateTime(now);
                merReportChange.setUpdateTime(now);
                merReportChangeMapper.insert(merReportChange);
            }

        } catch (Exception e) {
            log.error("send message of withdrawRecordClean is fail", e);
        }
        return true;
    }


    @Override
    public boolean withdrawRecordDeal(WithdrawRecordDealDto withdrawRecordDealDto) {

        int now = com.uzai.console.common.utils.DateUtil.getNowTime();

        //新提现状态（5拒绝并返还 6拒绝并扣除）
        Integer statusNew = withdrawRecordDealDto.getStatusNew();

        if (statusNew == null) {
            throw new BusinessException("请输入处理成状态");
        }

        if (withdrawRecordDealDto.getStatusOld() != TakeBalStatusEnum.TBS_PENDING.getValue()
           && withdrawRecordDealDto.getStatusOld() != TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue()) {
            throw new BusinessException("只支持待处理和自动提现失败的状态");
        }

        if (withdrawRecordDealDto.getStatusNew() != TakeBalStatusEnum.TBS_REFUSE_AND_RETURN.getValue()
                && withdrawRecordDealDto.getStatusNew() != TakeBalStatusEnum.TBS_REFUSE_AND_DEC.getValue()) {
            throw new BusinessException("只支持处理成拒绝并偿还和拒绝并扣除两种状态");
        }

        if (super.checkStartEndTimeIsHistoryQuery(withdrawRecordDealDto.getStartTime(), withdrawRecordDealDto.getEndTime(), null)) {
            String tableSuffix = DateTime.of(withdrawRecordDealDto.getEndTime() * 1000L).toString("yyMM");
            UserTakeBalQuery userTakeBalQuery = new UserTakeBalQuery();
            userTakeBalQuery.setMerId(withdrawRecordDealDto.getMerId());
            userTakeBalQuery.setStatus(withdrawRecordDealDto.getStatusOld());
            userTakeBalQuery.setQueryStartTime(withdrawRecordDealDto.getStartTime());
            userTakeBalQuery.setQueryEndTime(withdrawRecordDealDto.getEndTime());
            userTakeBalQuery.setUserId(withdrawRecordDealDto.getUserId());
            userTakeBalQuery.setSize(100);//一次最多处理100条
            userTakeBalQuery.setCurrent(1);
            UzaiRespVo<Page<UserTakeBal>> listUzaiRespVoRes = historyDataFeignService.pageTakeBalHistory(tableSuffix, userTakeBalQuery);
            if (listUzaiRespVoRes.getCode() != 200) {
                throw new BusinessException("提现列表查询失败");
            }
            if (listUzaiRespVoRes.getData() != null) {
                List<UserTakeBal> userTakeBalList = listUzaiRespVoRes.getData().getRecords();
                if (userTakeBalList != null && userTakeBalList.size() > 0) {
                    for (UserTakeBal userTakeBal : userTakeBalList) {
                        try {
                            userTakeBal.setStatus(statusNew);
                            userTakeBal.setUpdateTime(now);
                            UzaiRespVo<Boolean> uzaiRespVo_update = historyDataFeignService.edit(tableSuffix, userTakeBal);
                            logger.info("历史提现数据处理，tableSuffix={}, dto={}, result={}", tableSuffix, JSONObject.toJSONString(userTakeBal), JSONObject.toJSONString(uzaiRespVo_update));
                            if (uzaiRespVo_update != null && uzaiRespVo_update.getCode() == 200 && uzaiRespVo_update.getData()) {//修改成功
                                //拒绝并偿还,需要修改会员账号余额
                                if (statusNew == TakeBalStatusEnum.TBS_REFUSE_AND_RETURN.getValue()) {
                                    userAccDetailService.updateBalance(userTakeBal);
                                }
                            }
                        } catch (Exception e) {
                            logger.error("历史提现数据处理失败,id={},error={}", userTakeBal.getId(), e.getMessage());
                        }
                    }
                }
            }
        }
        // 反之查询90天内的订单数据
        else {
            throw new BusinessException("只支持历史数据处理");
        }

        return true;
    }

    public void sendMessage(WithdrawRecordCleanDto withdrawRecordCleanDto) {

        Long merId = withdrawRecordCleanDto.getMerId();

        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
        alarmMsgFeignDto.setMerId(merId);
        alarmMsgFeignDto.setType(SysMsgTypeEnum.OTHER_EXCEPTION.getValue());

        Merchant merchant = merchantService.findByMerId(merId);
        if (Objects.isNull(merchant)) {
            log.warn("sendMessage after withdrawRecordClean, merchant is not found. merId: {}", merId);
            return;
        }
        User userInfo = null;
        if (Objects.nonNull(withdrawRecordCleanDto.getUserId())) {
            userInfo = userService.findUserInfo(withdrawRecordCleanDto.getUserId(), null, merId);
            if (Objects.isNull(userInfo)) {
                log.warn("sendMessage after withdrawRecordClean, user is not found. userId: {}", withdrawRecordCleanDto.getUserId());
                return;
            }
        }

        //消息
        JSONObject ext = new JSONObject();

        StringBuilder content = new StringBuilder();
        // 判断是否为空
        if (Objects.nonNull(userInfo)) {
            content.append("正在清除[").append(userInfo.getId()).append("]的提现记录");
        } else {
            content.append("正在清除提现记录");
        }

        //当前操作员
        ext.put("content", content.toString());
        ext.put("phone", merchant.getMobile());
        ext.put("errorcode", content.toString());

        alarmMsgFeignDto.setExt(ext.toJSONString());
//        UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//        log.info("sendMessage after withdrawRecordClean result is: {}", JSON.toJSONString(uzaiRespVo));

        //2024-01-09修改成直接发送MQ
        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean keywordReplace(KeyWordsReplaceDto keyWordsReplaceDto) {

        // 根据运营商ID查询所有的配置
        List<SysPlugin> sysPluginList = sysPluginMapper.selectByMerId(keyWordsReplaceDto.getMerId());

        if (CollectionUtils.isEmpty(sysPluginList)) {
            return true;
        }
        String sourceKeyWord = keyWordsReplaceDto.getSourceKeyWord();
        String targetKeyWord = keyWordsReplaceDto.getTargetKeyWord();

        for (SysPlugin sysPlugin : sysPluginList) {

            JSONObject source;
            try {
                source = JSON.parseObject(sysPlugin.getData());
            } catch (Exception e) {
                log.error("keywordReplace parse sys_plugin json is fail, id: {}", sysPlugin.getId());
                log.error(e.getMessage(), e);
                continue;
            }
            doReplace(sourceKeyWord, targetKeyWord, source, (needEdit, result) -> {
                if (needEdit) {
                    String newJson = result.toJSONString();
                    sysPlugin.setData(newJson);
                    sysPluginMapper.update(sysPlugin);
                    // 更新缓存
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()), sysPlugin.getData(), 5, TimeUnit.DAYS);
                }
            });
        }
        // 处理cms配置
        handleCmsConfig(sourceKeyWord, targetKeyWord, keyWordsReplaceDto.getMerId());
        return true;
    }

    private void doReplace(String sourceKeyWord, String targetKeyWord, JSONObject jsonObject, BiConsumer<Boolean, JSONObject> callback) {
        boolean needEdit = false;
        for (Map.Entry<String, Object> stringObjectEntry : jsonObject.entrySet()) {

            Object value = stringObjectEntry.getValue();
            // 如果是字符串则替换, 否则直接聊过
            if (!(value instanceof String)) {
                continue;
            }
            String strValue = (String) value;
            // 判断是否存在指定来源字符串
            if (strValue.contains(sourceKeyWord)) {
                // 替换
                strValue = strValue.replace(sourceKeyWord, targetKeyWord);
                needEdit = true;
                // 更新
                stringObjectEntry.setValue(strValue);
            }
        }
        callback.accept(needEdit, jsonObject);
    }


    @Override
    public boolean faqReplyKeywordReplace(KeyWordsReplaceDto keyWordsReplaceDto) {
        //查询50条包含此关键词的智能回复语
        Page<FaqReply> page = new Page<>();
        page.setCurrent(1);//只查第一页
        page.setSize(50); //每页查询50个
        page.addOrder(OrderItem.asc("id"));//默认id升序
        Long idStart = 0L;

        FaqReplyQuery query = new FaqReplyQuery();
        query.setMerId(keyWordsReplaceDto.getMerId());
        query.setContent(keyWordsReplaceDto.getSourceKeyWord());

        List<FaqReply> faqReplyList = faqReplyMapper.findByList(page, query);

        if (CollectionUtils.isEmpty(faqReplyList)) {
            return true;
        }
        String sourceKeyWord = keyWordsReplaceDto.getSourceKeyWord();
        String targetKeyWord = keyWordsReplaceDto.getTargetKeyWord();

        for (FaqReply faqReply : faqReplyList) {
            String content = Tools.getStr(faqReply.getContent());
            //批量替换key为content的内容
            List<String> sourceKeyList = Lists.newArrayList("content", "cardTitle", "cardDes", "cardImg", "cardUrl");
            content = faqReplyDoReplace(content, sourceKeyList, keyWordsReplaceDto.getSourceKeyWord(), keyWordsReplaceDto.getTargetKeyWord());
            //修改
            faqReply.setContent(content);
            faqReplyMapper.updateById(faqReply);
        }
        return true;
    }

    /**
     * 递归替换智能回复语字符串内容
     *
     * @param content
     * @param sourceKeyList 只替换该key值
     * @param sourceKeyWord 替换旧关键词
     * @param sourceKeyWord 替换新关键词
     * @return
     */
    public String faqReplyDoReplace(String content, List<String> sourceKeyList, String sourceKeyWord, String targetKeyWord) {
        //判断此字符串是否是JSON对象
        if (Tools.isJSONObject(content)) {
            JSONObject jsonObject = JSONObject.parseObject(content);
            jsonObject = analysisJSONObject(jsonObject, sourceKeyList, sourceKeyWord, targetKeyWord);
            content = jsonObject.toJSONString();
        } else if (Tools.isJSONArray(content)) {
            JSONArray jsonArray = JSONArray.parseArray(content);
            jsonArray = analysisJSONArray(jsonArray, sourceKeyList, sourceKeyWord, targetKeyWord);
            content = jsonArray.toJSONString();
        } else { //字符串
            //字符串直接替换
            content = content.replaceAll(sourceKeyWord, targetKeyWord);
        }
        return content;
    }

    /**
     * 递归替换智能回复里的key为content的内容
     *
     * @param jsonObject
     * @return
     */
    public JSONObject analysisJSONObject(JSONObject jsonObject, List<String> sourceKeyList, String sourceKeyWord, String targetKeyWord) {
        JSONObject jsonObject_new = new JSONObject();
        Set<String> keys = jsonObject.keySet();
        for (String key : keys) {
            //依次遍历所有key,找到符合条件的key,则取出来替换
            Object value = jsonObject.get(key);
            if (Tools.isJSONObject(value.toString())) {
                JSONObject valueJsonObject = JSONObject.parseObject(value.toString());
                valueJsonObject = analysisJSONObject(valueJsonObject, sourceKeyList, sourceKeyWord, targetKeyWord);
                jsonObject_new.put(key, valueJsonObject);
            } else if (Tools.isJSONArray(value.toString())) {
                JSONArray jsonArray = JSONArray.parseArray(value.toString());
                if (jsonArray != null && jsonArray.size() > 0) {
                    jsonArray = analysisJSONArray(jsonArray, sourceKeyList, sourceKeyWord, targetKeyWord);
                    jsonObject_new.put(key, jsonArray);
                }
            } else {
                //找到最后的字符串，如果key等于sourceKey，则替换
                if (sourceKeyList.contains(key)) {
                    if (value != null) {
                        //替换之后的新字符串
                        String value_new = value.toString().replaceAll(sourceKeyWord, targetKeyWord);
                        jsonObject_new.put(key, value_new);
                    }
                } else {
                    jsonObject_new.put(key, value);
                }
            }
        }

        return jsonObject_new;
    }

    /**
     * 递归解析JSONArray
     *
     * @param jsonArray
     */
    public JSONArray analysisJSONArray(JSONArray jsonArray, List<String> sourceKeyList, String sourceKeyWord, String targetKeyWord) {
        JSONArray jsonArray_new = new JSONArray();
        for (Object json : jsonArray) {
            if (Tools.isJSONObject(json.toString())) {
                JSONObject valueJsonObject = JSONObject.parseObject(json.toString());
                valueJsonObject = analysisJSONObject(valueJsonObject, sourceKeyList, sourceKeyWord, targetKeyWord);
                jsonArray_new.add(valueJsonObject);
            } else if (Tools.isJSONArray(json.toString())) {
                JSONArray tmpJsonArray = JSONArray.parseArray(json.toString());
                if (tmpJsonArray != null && tmpJsonArray.size() > 0) {
                    tmpJsonArray = analysisJSONArray(jsonArray, sourceKeyList, sourceKeyWord, targetKeyWord);
                    jsonArray_new.add(tmpJsonArray);
                }
            }
        }
        return jsonArray_new;
    }

    private void handleCmsConfig(String sourceKeyWord, String targetKeyWord, Long merId) {
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.CMS_BASE_CONFIG.getValue());
        if (Objects.isNull(merBaseConfig)) {
            return;
        }

        JSONObject source;
        try {
            source = JSON.parseObject(merBaseConfig.getVal());
        } catch (Exception e) {
            log.error("keywordReplace parse merBaseConfig json is fail id: {}", merBaseConfig.getId());
            log.error(e.getMessage(), e);
            return;
        }

        doReplace(sourceKeyWord, targetKeyWord, source, (needEdit, result) -> {
            if (needEdit) {
                String newJson = result.toJSONString();
                merBaseConfig.setVal(newJson);
                merBaseConfigMapper.update(merBaseConfig);
                // 更新缓存
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.CMS_BASE_CONFIG.getKey(), merBaseConfig.getMerId()), merBaseConfig.getVal());
            }
        });
    }


    @Override
    public boolean addAutoCleanOrderStatusConfig(AutoCleanOrderStatusDto params) {

        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(params.getMerId(), MerConfigKeyEnum.DATA_HANDLE_HISTORY_ORDER_STATUS_CLEAN.getValue());
        // 新增
        if (Objects.isNull(merBaseConfig)) {
            merBaseConfig = new MerBaseConfig();
            merBaseConfig.setId(IdWorker.getId());
            merBaseConfig.setMerId(params.getMerId());
            merBaseConfig.setType(MerConfigTypeEnum.PRODUCTS.getValue());
            merBaseConfig.setKey(MerConfigKeyEnum.DATA_HANDLE_HISTORY_ORDER_STATUS_CLEAN.getValue());
            merBaseConfig.setVal(params.getConfigJson());

            int time = (int) (DateUtil.date().getTime() / 1000);
            merBaseConfig.setCreateTime(time);
            merBaseConfig.setUpdateTime(time);
            merBaseConfigMapper.insert(merBaseConfig);
        }
        // 更新
        else {
            merBaseConfig.setVal(params.getConfigJson());
            merBaseConfig.setUpdateTime((int) (DateUtil.date().getTime() / 1000));
            merBaseConfigMapper.update(merBaseConfig);
        }
        return true;
    }

    @Override
    public Object getAutoCleanOrderStatusConfig(Long merId) {
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.DATA_HANDLE_HISTORY_ORDER_STATUS_CLEAN.getValue());
        if (Objects.isNull(merBaseConfig)) {
            return new JSONArray();
        }
        return JSON.parseArray(merBaseConfig.getVal());
    }

    @Override
    //@Async("taskExecutor")
    public void cleanOrderStatus(CleanOrderStatusDto params) {

        Integer type = params.getType();
        Integer startTime = params.getStartTime();
        Integer endTime = params.getEndTime();

        //订单状态, 2: 失效, 1: 结算
        Integer status = Tools.getInteger(params.getStatus());
        if (status == null) {//如果订单状态为空，则默认改为订单结算（兼容旧版）
            status = 1; //
        }
        //是否结算, 0: 不结算, 1: 从平台更新状态结算， 2；直接结算
        Integer settle = Tools.getInteger(params.getSettle());

        //来源状态(涉及两个字段), 1: 未收货 - 订单状态, 2: 冻结 - 订单返利状态，3-维权中
        List<Integer> sourceStatus = params.getSourceStatus();

        //运营商
        Long merId = params.getMerId();
        //会员id
        Long userId = params.getUserId();

        // 三月前的时间
        int threeMonthBefore = (int) (DateTime.now().offset(DateField.MONTH, -3).getTime() / 1000);
        switch (type) {
            case 1:
                // 清理历史订单，判断开始时间是否在三个月前，如果是，则历史订单全部清除
                if (startTime.intValue() < threeMonthBefore) {
                    historyDataFeignService.editStatusBatch(params.getMerId(), params.getUserId(), params.getSourceStatus(), params.getStatus());
                }

                //修改成结算，需要判断按实际结算，还是只修改订单状态
                if (status == 1) {
                    if (settle == 0) { //不结算，直接订单状态为已经结算
                        // 清理三个月内的订单
                        tbOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                    } else if (settle == 1) {//结算，重新请求同步订单接口
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                tbOrderSyncService.updateTbOrderUnReceivedListSync(merId, startTime, endTime, userId);
                            }
                            //冻结订单
                            if (sourceStatus.contains(2)) {
                                tbOrderSyncService.updateTbOrderFreezedListSync(merId, startTime, endTime, userId);
                            }
                            //维权中
                            if (sourceStatus.contains(3)) {
                                tbOrderSyncService.updateTbOrderRefundingListSync(merId, startTime, endTime, userId);
                            }
                        }
                    } else if (settle == 2) {//不更新订单，直接结算
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                tbOrderSyncService.updateTbOrderUnReceivedListSync_settle(merId, startTime, endTime, userId);
                            }
                            //冻结订单
                            if (sourceStatus.contains(2)) {
                                tbOrderSyncService.updateTbOrderFreezedListSync_settle(merId, startTime, endTime, userId);
                            }
                            //维权中订单
                            if (sourceStatus.contains(3)) {
                                tbOrderSyncService.updateTbOrderRefundingListSync_settle(merId, startTime, endTime, userId);
                            }
                        }
                    }
                } else if (status == 2) {//修改成失效，则只需要修改订单状态，无需实际结算
                    // 清理三个月内的订单
                    tbOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                }
                break;
            case 2:
                //修改成结算，需要判断按实际结算，还是只修改订单状态
                if (status == 1) {
                    if (settle == 0) { //不结算，直接订单状态为已经结算
                        // 清理三个月内的订单
                        jdOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                    } else if (settle == 1) {//结算，重新请求同步订单接口
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                jdOrderSyncService.updateJdOrderUnReceivedListSync(merId, startTime, endTime, userId);
                            }
                            //冻结订单
                            if (sourceStatus.contains(2)) {
                                jdOrderSyncService.updateJdOrderFreezedListSync(merId, startTime, endTime, userId);
                            }
                            //维权中订单
                            if (sourceStatus.contains(3)) {
                                jdOrderSyncService.updateJdOrderRefundingListSync(merId, startTime, endTime, userId);
                            }
                        }
                    } else if (settle == 2) {//不更新订单，直接结算
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                jdOrderSyncService.updateJdOrderUnReceivedListSync_settle(merId, startTime, endTime, userId);
                            }
                            //冻结中订单
                            if (sourceStatus.contains(2)) {
                                jdOrderSyncService.updateJdOrderFreezedListSync_settle(merId, startTime, endTime, userId);
                            }
                            //维权中订单
                            if (sourceStatus.contains(3)) {
                                jdOrderSyncService.updateJdOrderRefundingListSync_settle(merId, startTime, endTime, userId);
                            }
                        }
                    }
                } else if (status == 2) {//修改成失效，则只需要修改订单状态，无需实际结算
                    // 清理三个月内的订单
                    jdOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                }
                break;
            case 3:
                //修改成结算，需要判断按实际结算，还是只修改订单状态
                if (status == 1) {
                    if (settle == 0) { //不结算，直接订单状态为已经结算
                        // 清理三个月内的订单
                        pddOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                    } else if (settle == 1) {//结算，重新请求同步订单接口
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                pddOrderSyncService.updatePddOrderUnReceivedListSync(merId, startTime, endTime, userId);
                            }
                            //冻结订单
                            if (sourceStatus.contains(2)) {
                                pddOrderSyncService.updatePddOrderFreezedListSync(merId, startTime, endTime, userId);
                            }
                            //维权中订单
                            if (sourceStatus.contains(3)) {
                                pddOrderSyncService.updatePddOrderRefundingListSync(merId, startTime, endTime, userId);
                            }
                        }
                    } else if (settle == 2) {//不更新订单，直接结算
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                pddOrderSyncService.updatePddOrderUnReceivedListSync_settle(merId, startTime, endTime, userId);
                            }
                            //已冻结订单
                            if (sourceStatus.contains(2)) {
                                pddOrderSyncService.updatePddOrderFreezedListSync_settle(merId, startTime, endTime, userId);
                            }
                            //维权中订单
                            if (sourceStatus.contains(3)) {
                                pddOrderSyncService.updatePddOrderRefundingListSync_settle(merId, startTime, endTime, userId);
                            }
                        }
                    }
                } else if (status == 2) {//修改成失效，则只需要修改订单状态，无需实际结算
                    // 清理三个月内的订单
                    pddOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                }
                break;
            case 4:
                //修改成结算，需要判断按实际结算，还是只修改订单状态
                if (status == 1) {
                    if (settle == 0) { //不结算，直接订单状态为已经结算
                        // 清理三个月内的订单
                        vphOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                    } else if (settle == 1) {//结算，重新请求同步订单接口
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                vphOrderSyncService.updateVphOrderUnReceivedListSync(merId, startTime, endTime, userId);
                            }
                            //冻结订单
                            if (sourceStatus.contains(2)) {
                                vphOrderSyncService.updateVphOrderFreezedListSync(merId, startTime, endTime, userId);
                            }
                            //维权中订单
                            if (sourceStatus.contains(3)) {
                                vphOrderSyncService.updateVphOrderRefundingListSync(merId, startTime, endTime, userId);
                            }
                        }
                    } else if (settle == 2) {//不更新订单，直接结算
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                vphOrderSyncService.updateVphOrderUnReceivedListSync_settle(merId, startTime, endTime, userId);
                            }
                            //已冻结订单
                            if (sourceStatus.contains(2)) {
                                vphOrderSyncService.updateVphOrderFreezedListSync_settle(merId, startTime, endTime, userId);
                            }
                            //维权中订单
                            if (sourceStatus.contains(3)) {
                                vphOrderSyncService.updateVphOrderRefundingListSync_settle(merId, startTime, endTime, userId);
                            }
                        }
                    }
                } else if (status == 2) {//修改成失效，则只需要修改订单状态，无需实际结算
                    // 清理三个月内的订单
                    vphOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                }
                break;
            case 5:
                //修改成结算，需要判断按实际结算，还是只修改订单状态
                if (status == 1) {
                    if (settle == 0) { //不结算，直接订单状态为已经结算
                        // 清理三个月内的订单
                        dyOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                    } else if (settle == 1) {//结算，重新请求同步订单接口
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                dyOrderSyncService.updateDyOrderUnReceivedListSync(merId, startTime, endTime, userId);
                            }
                            //冻结订单
                            if (sourceStatus.contains(2)) {
                                dyOrderSyncService.updateDyOrderFreezedListSync(merId, startTime, endTime, userId);
                            }
                            //维权中订单
                            if (sourceStatus.contains(3)) {
                                dyOrderSyncService.updateDyOrderRefundingListSync(merId, startTime, endTime, userId);
                            }
                        }
                    } else if (settle == 2) {//不更新订单，直接结算
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                dyOrderSyncService.updateDyOrderUnReceivedListSync_settle(merId, startTime, endTime, userId);
                            }

                            //已冻结订单
                            if (sourceStatus.contains(2)) {
                                dyOrderSyncService.updateDyOrderFreezedListSync_settle(merId, startTime, endTime, userId);
                            }

                            //维权中订单
                            if (sourceStatus.contains(3)) {
                                dyOrderSyncService.updateDyOrderRefundingListSync_settle(merId, startTime, endTime, userId);
                            }
                        }
                    }
                } else if (status == 2) {//修改成失效，则只需要修改订单状态，无需实际结算
                    // 清理三个月内的订单
                    dyOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                }
                break;
            case 6:
                //修改成结算，需要判断按实际结算，还是只修改订单状态
                if (status == 1) {
                    if (settle == 0) { //不结算，直接订单状态为已经结算
                        // 清理三个月内的订单
                        mtOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                    } else if (settle == 1) {//结算，重新请求同步订单接口
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                mtOrderSyncService.updateMtOrderUnReceivedListSync(merId, startTime, endTime, userId);
                            }
                            //冻结订单
                            if (sourceStatus.contains(2)) {
                                mtOrderSyncService.updateMtOrderFreezedListSync(merId, startTime, endTime, userId);
                            }
                            //维权中订单
                            if (sourceStatus.contains(3)) {
                                mtOrderSyncService.updateMtOrderRefundingListSync(merId, startTime, endTime, userId);
                            }
                        }
                    } else if (settle == 2) {//不更新订单，直接结算
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                mtOrderSyncService.updateMtOrderUnReceivedListSync_settle(merId, startTime, endTime, userId);
                            }
                            //已冻结订单
                            if (sourceStatus.contains(2)) {
                                mtOrderSyncService.updateMtOrderFreezedListSync_settle(merId, startTime, endTime, userId);
                            }
                            //维权中订单
                            if (sourceStatus.contains(3)) {
                                mtOrderSyncService.updateMtOrderRefundingListSync_settle(merId, startTime, endTime, userId);
                            }
                        }
                    }
                } else if (status == 2) {//修改成失效，则只需要修改订单状态，无需实际结算
                    // 清理三个月内的订单
                    mtOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                }
                break;
            case 7:
                //修改成结算，需要判断按实际结算，还是只修改订单状态
                if (status == 1) {
                    if (settle == 0) { //不结算，直接订单状态为已经结算
                        // 清理三个月内的订单
                        elmOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                    } else if (settle == 1) {//结算，重新请求同步订单接口
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                elmOrderSyncService.updateElmOrderUnReceivedListSync(merId, startTime, endTime, userId);
                            }
                            //冻结订单
                            if (sourceStatus.contains(2)) {
                                elmOrderSyncService.updateElmOrderFreezedListSync(merId, startTime, endTime, userId);
                            }
                            //维权中订单
                            if (sourceStatus.contains(3)) {
                                elmOrderSyncService.updateElmOrderRefundingListSync(merId, startTime, endTime, userId);
                            }
                        }
                    } else if (settle == 2) {//不更新订单，直接结算
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                elmOrderSyncService.updateElmOrderUnReceivedListSync_settle(merId, startTime, endTime, userId);
                            }
                            //已冻结订单
                            if (sourceStatus.contains(2)) {
                                elmOrderSyncService.updateElmOrderFreezedListSync_settle(merId, startTime, endTime, userId);
                            }
                            //维权中订单
                            if (sourceStatus.contains(3)) {
                                elmOrderSyncService.updateElmOrderRefundingListSync_settle(merId, startTime, endTime, userId);
                            }
                        }
                    }
                } else if (status == 2) {//修改成失效，则只需要修改订单状态，无需实际结算
                    // 清理三个月内的订单
                    elmOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                }
                break;
            case 8:
                //修改成结算，需要判断按实际结算，还是只修改订单状态
                if (status == 1) {
                    if (settle == 0) { //不结算，直接订单状态为已经结算
                        // 清理三个月内的订单
                        ksOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                    } else if (settle == 1) {//结算，重新请求同步订单接口
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                ksOrderSyncService.updateKsOrderUnReceivedListSync(merId, startTime, endTime, userId);
                            }
                            //冻结订单
                            if (sourceStatus.contains(2)) {
                                ksOrderSyncService.updateKsOrderFreezedListSync(merId, startTime, endTime, userId);
                            }
                            //维权中订单
                            if (sourceStatus.contains(3)) {
                                ksOrderSyncService.updateKsOrderRefundingListSync(merId, startTime, endTime, userId);
                            }
                        }
                    } else if (settle == 2) {//不更新订单，直接结算
                        if (sourceStatus != null && sourceStatus.size() > 0) {
                            //未收货订单
                            if (sourceStatus.contains(1)) {
                                ksOrderSyncService.updateKsOrderUnReceivedListSync_settle(merId, startTime, endTime, userId);
                            }
                            //已冻结订单
                            if (sourceStatus.contains(2)) {
                                ksOrderSyncService.updateKsOrderFreezedListSync_settle(merId, startTime, endTime, userId);
                            }
                            //维权中订单
                            if (sourceStatus.contains(3)) {
                                ksOrderSyncService.updateKsOrderRefundingListSync_settle(merId, startTime, endTime, userId);
                            }
                        }
                    }
                } else if (status == 2) {//修改成失效，则只需要修改订单状态，无需实际结算
                    // 清理三个月内的订单
                    ksOrderMapper.updateStatusPayCompleteToSettle(startTime, endTime, params.getUserId(), params.getMerId(), params.getStatus(), params.getSourceStatus());
                }
                break;
            default:
                throw new BusinessException("订单类型错误");
        }

        //增加运营商报表改变记录
        //查询提现记录报表记录存不存在，存在则不添加
        MerReportChange merReportChange = merReportChangeMapper.selectByMerIdAndType(params.getMerId(), 1);
        if(merReportChange == null){
            int now = com.uzai.console.common.utils.DateUtil.getNowTime();
            merReportChange = new MerReportChange();
            merReportChange.setId(IdWorker.getId());
            merReportChange.setMerId(IdWorker.getId());
            merReportChange.setType(1);
            merReportChange.setRemark("数据处理-订单状态处理");
            merReportChange.setCreateTime(now);
            merReportChange.setUpdateTime(now);
            merReportChangeMapper.insert(merReportChange);
        }

    }

    /**
     * 会员数据合并
     *
     * @param userDataMergeDto
     * @return
     */
    @Override
    @Transactional
    public void userDataMerge(UserDataMergeDto userDataMergeDto) {

        User userOld = userService.findUserInfo(userDataMergeDto.getUserIdOld(), null, userDataMergeDto.getMerId());
        if (userOld == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "旧会员不存在");
        }

        User userNew = userService.findUserInfo(userDataMergeDto.getUserIdNew(), null, userDataMergeDto.getMerId());
        if (userNew == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新会员不存在");
        }

        if (!userOld.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())) {
            //throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只支持个人微信会员合并");
        }

        //如果会员对应的机器人类型不一样
        if (!Tools.getStr(userOld.getDeviceType()).equals(Tools.getStr(userNew.getDeviceType()))) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新旧会员对应的机器人平台不一样");
        }


        //处理各平台订单
        //合并淘宝订单
        try {
            TbOrderQuery tbOrderQuery = new TbOrderQuery();
            tbOrderQuery.setMerId(userOld.getMerId());
            tbOrderQuery.setUserId(userOld.getId());
            List<TbOrder> tbOrderList = tbOrderMapper.findByList(tbOrderQuery);
            if(tbOrderList != null && tbOrderList.size() > 0){
                for (TbOrder tbOrder : tbOrderList) {
                    //清除订单返利ES数据
                    String rewardInfoId = tbOrder.getMerId() + "_" + tbOrder.getParentOrderNo() + "_" + tbOrder.getChildOrderNo();
                    elasticsearchUtil.deleteDataById(EsIndexName.UZAI_ORDER_REWARD_INFO, rewardInfoId);
                }
                tbOrderMapper.tbOrderMerge(userDataMergeDto.getUserIdOld(), userDataMergeDto.getUserIdNew(), userDataMergeDto.getMerId());
            }
        }catch (Exception e){

        }



        //合并京东京东
        try {
            JdOrderQuery jdOrderQuery = new JdOrderQuery();
            jdOrderQuery.setMerId(userOld.getMerId());
            jdOrderQuery.setUserId(userOld.getId());
            List<JdOrder> jdOrderList = jdOrderMapper.findByList(jdOrderQuery);
            if(jdOrderList != null && jdOrderList.size() > 0){
                for (JdOrder jdOrder : jdOrderList) {
                    //清除订单返利ES数据
                    String rewardInfoId = jdOrder.getMerId() + "_" + jdOrder.getParentOrderNo() + "_" + jdOrder.getChildOrderNo();
                    elasticsearchUtil.deleteDataById(EsIndexName.UZAI_ORDER_REWARD_INFO, rewardInfoId);
                }
                jdOrderMapper.jdOrderMerge(userDataMergeDto.getUserIdOld(), userDataMergeDto.getUserIdNew(), userDataMergeDto.getMerId());
            }
        }catch (Exception e){

        }

        //合并拼多多订单
        try {
            PddOrderQuery pddOrderQuery = new PddOrderQuery();
            pddOrderQuery.setMerId(userOld.getMerId());
            pddOrderQuery.setUserId(userOld.getId());
            List<PddOrder> pddOrderList = pddOrderMapper.findByList(pddOrderQuery);
            if(pddOrderList != null && pddOrderList.size() > 0){
                for (PddOrder pddOrder : pddOrderList) {
                    //清除订单返利ES数据
                    String rewardInfoId = pddOrder.getMerId() + "_" + pddOrder.getParentOrderNo() + "_" + pddOrder.getChildOrderNo();
                    elasticsearchUtil.deleteDataById(EsIndexName.UZAI_ORDER_REWARD_INFO, rewardInfoId);
                }
                pddOrderMapper.pddOrderMerge(userDataMergeDto.getUserIdOld(), userDataMergeDto.getUserIdNew(), userDataMergeDto.getMerId());
            }
        }catch (Exception e){

        }

        //合并唯品会订单
        try {
            VphOrderQuery vphOrderQuery = new VphOrderQuery();
            vphOrderQuery.setMerId(userOld.getMerId());
            vphOrderQuery.setUserId(userOld.getId());
            List<VphOrder> vphOrderList = vphOrderMapper.findByList(vphOrderQuery);
            if(vphOrderList != null && vphOrderList.size() > 0){
                for (VphOrder vphOrder : vphOrderList) {
                    //清除订单返利ES数据
                    String rewardInfoId = vphOrder.getMerId() + "_" + vphOrder.getParentOrderNo() + "_" + vphOrder.getChildOrderNo();
                    elasticsearchUtil.deleteDataById(EsIndexName.UZAI_ORDER_REWARD_INFO, rewardInfoId);
                }
                vphOrderMapper.vphOrderMerge(userDataMergeDto.getUserIdOld(), userDataMergeDto.getUserIdNew(), userDataMergeDto.getMerId());
            }
        }catch (Exception e){

        }


        //合并抖音订单
        try {
            DyOrderQuery dyOrderQuery = new DyOrderQuery();
            dyOrderQuery.setMerId(userOld.getMerId());
            dyOrderQuery.setUserId(userOld.getId());
            List<DyOrder> dyOrderList = dyOrderMapper.findByList(dyOrderQuery);
            if(dyOrderList != null && dyOrderList.size() > 0){
                for (DyOrder dyOrder : dyOrderList) {
                    //清除订单返利ES数据
                    String rewardInfoId = dyOrder.getMerId() + "_" + dyOrder.getParentOrderNo() + "_" + dyOrder.getChildOrderNo();
                    elasticsearchUtil.deleteDataById(EsIndexName.UZAI_ORDER_REWARD_INFO, rewardInfoId);
                }
                dyOrderMapper.dyOrderMerge(userDataMergeDto.getUserIdOld(), userDataMergeDto.getUserIdNew(), userDataMergeDto.getMerId());
            }
        }catch (Exception e){

        }

        //合并快手订单
        try {
            KsOrderQuery ksOrderQuery = new KsOrderQuery();
            ksOrderQuery.setMerId(userOld.getMerId());
            ksOrderQuery.setUserId(userOld.getId());
            List<KsOrder> ksOrderList = ksOrderMapper.findByList(ksOrderQuery);
            if(ksOrderList != null && ksOrderList.size() > 0){
                for (KsOrder ksOrder : ksOrderList) {
                    //清除订单返利ES数据
                    String rewardInfoId = ksOrder.getMerId() + "_" + ksOrder.getParentOrderNo() + "_" + ksOrder.getChildOrderNo();
                    elasticsearchUtil.deleteDataById(EsIndexName.UZAI_ORDER_REWARD_INFO, rewardInfoId);
                }
                ksOrderMapper.ksOrderMerge(userDataMergeDto.getUserIdOld(), userDataMergeDto.getUserIdNew(), userDataMergeDto.getMerId());
            }
        }catch (Exception e){

        }

        //合并美团订单
        try {
            MtOrderQuery mtOrderQuery = new MtOrderQuery();
            mtOrderQuery.setMerId(userOld.getMerId());
            mtOrderQuery.setUserId(userOld.getId());
            List<MtOrder> mtOrderList = mtOrderMapper.findByList(mtOrderQuery);
            if(mtOrderList != null && mtOrderList.size() > 0){
                for (MtOrder mtOrder : mtOrderList) {
                    //清除订单返利ES数据
                    String rewardInfoId = mtOrder.getMerId() + "_" + mtOrder.getParentOrderNo() + "_" + mtOrder.getChildOrderNo();
                    elasticsearchUtil.deleteDataById(EsIndexName.UZAI_ORDER_REWARD_INFO, rewardInfoId);
                }
                mtOrderMapper.mtOrderMerge(userDataMergeDto.getUserIdOld(), userDataMergeDto.getUserIdNew(), userDataMergeDto.getMerId());
            }
        }catch (Exception e){

        }

        //合并饿了么订单
        try {
            ElmOrderQuery elmOrderQuery = new ElmOrderQuery();
            elmOrderQuery.setMerId(userOld.getMerId());
            elmOrderQuery.setUserId(userOld.getId());
            List<ElmOrder> elmOrderList = elmOrderMapper.findByList(elmOrderQuery);
            if(elmOrderList != null && elmOrderList.size() > 0){
                for (ElmOrder elmOrder : elmOrderList) {
                    //清除订单返利ES数据
                    String rewardInfoId = elmOrder.getMerId() + "_" + elmOrder.getParentOrderNo() + "_" + elmOrder.getChildOrderNo();
                    elasticsearchUtil.deleteDataById(EsIndexName.UZAI_ORDER_REWARD_INFO, rewardInfoId);
                }
                elmOrderMapper.elmOrderMerge(userDataMergeDto.getUserIdOld(), userDataMergeDto.getUserIdNew(), userDataMergeDto.getMerId());
            }
        }catch (Exception e){

        }

        //合并会员积分余额
        int now = com.uzai.common.utils.DateUtil.getTime();
        //修改用户余额和微信id
        if (userOld.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())) { //个人微信用户
            //互换会员微信id（将旧会员微信id保存新会员微信id，新会员微信id保存到旧会员微信id）
            //String wxid_userOld = userOld.getBizUserId();
            //String wxid_userNew = userNew.getBizUserId();

            WechatUser wechatUserOld = wechatUserMapper.selectById(userOld.getId(), userOld.getMerId());
            if (wechatUserOld == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信旧用户不存在");
            }

            //修改微信id
            //wechatUserOld.setWxid(wxid_userNew + "_console_merge");
            //修改用户业务终端唯一id
            //wechatUserOld.setBizUserId(wxid_userNew+"_console_merge");
            //计算用户余额并修改
            Double oldBalance_oldUser = wechatUserOld.getBalance();
            //计算用户余额并修改
            Integer oldIntegral_oldUser = wechatUserOld.getIntegral();
            //修改余额
            Double newBalance_oldUser = 0.00D;
            Integer newIntegral_oldUser = 0;
            wechatUserOld.setBalance(newBalance_oldUser);
            wechatUserOld.setIntegral(newIntegral_oldUser);
            wechatUserOld.setUpdateTime(now);
            int i = wechatUserMapper.updateBalance(wechatUserOld);

            if (i == 1) {
                //增加旧会员账号出账明细
                UserAccDetail wechatUserAccDetail_oldUser = new UserAccDetail();
                wechatUserAccDetail_oldUser.setId(IdWorker.getId());
                wechatUserAccDetail_oldUser.setMerId(wechatUserOld.getMerId());
                wechatUserAccDetail_oldUser.setUserId(wechatUserOld.getId());
                wechatUserAccDetail_oldUser.setDeviceUniqueId(wechatUserOld.getDeviceUniqueId());
                wechatUserAccDetail_oldUser.setDeviceType(wechatUserOld.getDeviceType());
                wechatUserAccDetail_oldUser.setChangeInte(oldIntegral_oldUser);
                wechatUserAccDetail_oldUser.setChangeBal(oldBalance_oldUser);
                wechatUserAccDetail_oldUser.setNewBal(newBalance_oldUser);
                wechatUserAccDetail_oldUser.setNewInte(newIntegral_oldUser);
                wechatUserAccDetail_oldUser.setType(AccDetailTypeEnum.MERGE_SUB.getValue());
                wechatUserAccDetail_oldUser.setTradeno(IdWorker.getIdStr());
                wechatUserAccDetail_oldUser.setRemark(null);
                wechatUserAccDetail_oldUser.setCreateTime(now);
                wechatUserAccDetail_oldUser.setUpdateTime(now);
                int insert = userAccDetailMapper.insert(wechatUserAccDetail_oldUser);
                if (insert != 1) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
                }
            } else {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
            }

            //新会员
            WechatUser wechatUserNew = wechatUserMapper.selectById(userNew.getId(), userNew.getMerId());
            if (wechatUserNew == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信新用户不存在");
            }

            //修改微信id
            //wechatUserNew.setWxid(wxid_userOld);
            //修改用户业务终端唯一id
            //wechatUserNew.setBizUserId(wxid_userOld);
            //计算用户余额并修改
            Double oldBalance_newUser = wechatUserNew.getBalance();
            Integer oldIntegral_newUser = wechatUserNew.getIntegral();
            //修改余额
            Double newBalance_newUser = Math.add(oldBalance_newUser, oldBalance_oldUser);
            Integer newIntegral_newUser = oldIntegral_newUser + oldIntegral_oldUser;
            wechatUserNew.setBalance(newBalance_newUser);
            wechatUserNew.setIntegral(newIntegral_newUser);
            wechatUserNew.setUpdateTime(now);
            int j = wechatUserMapper.updateBalance(wechatUserNew);
            if (j == 1) {
                //增加新会员账号入账明细
                UserAccDetail wechatUserAccDetail_newUser = new UserAccDetail();
                wechatUserAccDetail_newUser.setId(IdWorker.getId());
                wechatUserAccDetail_newUser.setMerId(wechatUserNew.getMerId());
                wechatUserAccDetail_newUser.setUserId(wechatUserNew.getId());
                wechatUserAccDetail_newUser.setDeviceUniqueId(wechatUserOld.getDeviceUniqueId());
                wechatUserAccDetail_newUser.setDeviceType(wechatUserOld.getDeviceType());
                wechatUserAccDetail_newUser.setChangeInte(oldIntegral_oldUser);
                wechatUserAccDetail_newUser.setChangeBal(oldBalance_oldUser);
                wechatUserAccDetail_newUser.setNewBal(newBalance_newUser);
                wechatUserAccDetail_newUser.setNewInte(newIntegral_newUser);
                wechatUserAccDetail_newUser.setType(AccDetailTypeEnum.MERGE_ADD.getValue());
                wechatUserAccDetail_newUser.setTradeno(IdWorker.getIdStr());
                wechatUserAccDetail_newUser.setRemark(null);
                wechatUserAccDetail_newUser.setCreateTime(now);
                wechatUserAccDetail_newUser.setUpdateTime(now);
                int insert = userAccDetailMapper.insert(wechatUserAccDetail_newUser);
                if (insert != 1) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
                }
            } else {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
            }

//            //修改ES缓存
//            try{
//
//                //删除缓存
//                redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WX_USER_ID.getKey(), userOld.getMerId(), wxid_userOld));
//
//                //修改会员ES信息
//                String uzai_user_info_id = DeviceTypeEnum.DT_PC_WECHAT.getKey() + "_" + userOld.getMerId() + "_" + wxid_userOld;
//                String uzai_user_info = merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_INFO, userOld.getMerId());
//                Map<String,Object> dataMp_userInfo = elasticsearchUtil.searchDataById(uzai_user_info, uzai_user_info_id, null);
//                if(dataMp_userInfo != null){
//                    JSONObject jsonObject = new JSONObject();
//                    jsonObject.put("userId", userNew.getId());  //将新会员id更新到ES当中
//                    jsonObject.put("updateTime", now);
//                    elasticsearchUtil.updateDataById(jsonObject, uzai_user_info, uzai_user_info_id);
//                }
//
//                //修改会员ES扩展信息
//                String uzai_user_ext_info_id = DeviceTypeEnum.DT_PC_WECHAT.getKey() + "_" + userOld.getMerId() + "_" + wxid_userOld;
//                String uzai_user_ext_info = merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, userOld.getMerId());
//                Map<String,Object> dataMp_ext = elasticsearchUtil.searchDataById(uzai_user_ext_info, uzai_user_ext_info_id, null);
//                if(dataMp_ext != null){
//                    JSONObject jsonObject = new JSONObject();
//                    jsonObject.put("userId", userNew.getId());  //将新会员更新到ES当中
//                    jsonObject.put("updateTime", now);
//                    elasticsearchUtil.updateDataById(jsonObject, uzai_user_ext_info, uzai_user_ext_info_id);
//                }
//
//            }catch (Exception e){
//                log.info("--会员数据合并---修改会员ES扩展信息失败--", e);
//                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
//            }

        } else if (userOld.getDeviceType().equals(DeviceTypeEnum.DT_WORK_WECHAT.getKey())) { //企业微信
            //互换会员微信id（将旧会员微信id保存新会员微信id，新会员微信id保存到旧会员微信id）
            //String wxid_userOld = userOld.getBizUserId();
            //String wxid_userNew = userNew.getBizUserId();

            WxworkUser wxworkUserOld = wxworkUserMapper.selectById(userOld.getId(), userOld.getMerId());
            if (wxworkUserOld == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信旧用户不存在");
            }

            //修改微信id
            //wechatUserOld.setWxid(wxid_userNew + "_console_merge");
            //修改用户业务终端唯一id
            //wechatUserOld.setBizUserId(wxid_userNew+"_console_merge");
            //计算用户余额并修改
            Double oldBalance_oldUser = wxworkUserOld.getBalance();
            //计算用户余额并修改
            Integer oldIntegral_oldUser = wxworkUserOld.getIntegral();
            //修改余额
            Double newBalance_oldUser = 0.00D;
            Integer newIntegral_oldUser = 0;
            wxworkUserOld.setBalance(newBalance_oldUser);
            wxworkUserOld.setIntegral(newIntegral_oldUser);
            wxworkUserOld.setUpdateTime(now);
            int i = wxworkUserMapper.updateBalance(wxworkUserOld);

            if (i == 1) {
                //增加旧会员账号出账明细
                UserAccDetail wechatUserAccDetail_oldUser = new UserAccDetail();
                wechatUserAccDetail_oldUser.setId(IdWorker.getId());
                wechatUserAccDetail_oldUser.setMerId(wxworkUserOld.getMerId());
                wechatUserAccDetail_oldUser.setUserId(wxworkUserOld.getId());
                wechatUserAccDetail_oldUser.setDeviceUniqueId(wxworkUserOld.getDeviceUniqueId());
                wechatUserAccDetail_oldUser.setDeviceType(wxworkUserOld.getDeviceType());
                wechatUserAccDetail_oldUser.setChangeInte(oldIntegral_oldUser);
                wechatUserAccDetail_oldUser.setChangeBal(oldBalance_oldUser);
                wechatUserAccDetail_oldUser.setNewBal(newBalance_oldUser);
                wechatUserAccDetail_oldUser.setNewInte(newIntegral_oldUser);
                wechatUserAccDetail_oldUser.setType(AccDetailTypeEnum.MERGE_SUB.getValue());
                wechatUserAccDetail_oldUser.setTradeno(IdWorker.getIdStr());
                wechatUserAccDetail_oldUser.setRemark(null);
                wechatUserAccDetail_oldUser.setCreateTime(now);
                wechatUserAccDetail_oldUser.setUpdateTime(now);
                int insert = userAccDetailMapper.insert(wechatUserAccDetail_oldUser);
                if (insert != 1) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
                }
            } else {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
            }

            //新会员
            WxworkUser wxworkUserNew = wxworkUserMapper.selectById(userNew.getId(), userNew.getMerId());
            if (wxworkUserNew == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信新用户不存在");
            }

            //修改微信id
            //wechatUserNew.setWxid(wxid_userOld);
            //修改用户业务终端唯一id
            //wechatUserNew.setBizUserId(wxid_userOld);
            //计算用户余额并修改
            Double oldBalance_newUser = wxworkUserNew.getBalance();
            Integer oldIntegral_newUser = wxworkUserNew.getIntegral();
            //修改余额
            Double newBalance_newUser = Math.add(oldBalance_newUser, oldBalance_oldUser);
            Integer newIntegral_newUser = oldIntegral_newUser + oldIntegral_oldUser;
            wxworkUserNew.setBalance(newBalance_newUser);
            wxworkUserNew.setIntegral(newIntegral_newUser);
            wxworkUserNew.setUpdateTime(now);
            int j = wxworkUserMapper.updateBalance(wxworkUserNew);
            if (j == 1) {
                //增加新会员账号入账明细
                UserAccDetail wechatUserAccDetail_newUser = new UserAccDetail();
                wechatUserAccDetail_newUser.setId(IdWorker.getId());
                wechatUserAccDetail_newUser.setMerId(wxworkUserNew.getMerId());
                wechatUserAccDetail_newUser.setUserId(wxworkUserNew.getId());
                wechatUserAccDetail_newUser.setDeviceUniqueId(wxworkUserNew.getDeviceUniqueId());
                wechatUserAccDetail_newUser.setDeviceType(wxworkUserNew.getDeviceType());
                wechatUserAccDetail_newUser.setChangeInte(oldIntegral_oldUser);
                wechatUserAccDetail_newUser.setChangeBal(oldBalance_oldUser);
                wechatUserAccDetail_newUser.setNewBal(newBalance_newUser);
                wechatUserAccDetail_newUser.setNewInte(newIntegral_newUser);
                wechatUserAccDetail_newUser.setType(AccDetailTypeEnum.MERGE_ADD.getValue());
                wechatUserAccDetail_newUser.setTradeno(IdWorker.getIdStr());
                wechatUserAccDetail_newUser.setRemark(null);
                wechatUserAccDetail_newUser.setCreateTime(now);
                wechatUserAccDetail_newUser.setUpdateTime(now);
                int insert = userAccDetailMapper.insert(wechatUserAccDetail_newUser);
                if (insert != 1) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
                }
            } else {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
            }
        } else if (userOld.getDeviceType().equals(DeviceTypeEnum.WX_PUB.getKey())) {//公众号用户

            WxpubUser wxpubUserOld = wxpubUserMapper.selectById(userOld.getId(), userOld.getMerId());
            if (wxpubUserOld == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该公众号微信旧用户不存在");
            }

            //计算用户余额并修改
            Double oldBalance_oldUser = wxpubUserOld.getBalance();
            //计算用户余额并修改
            Integer oldIntegral_oldUser = wxpubUserOld.getIntegral();
            //修改余额
            Double newBalance_oldUser = 0.00D;
            Integer newIntegral_oldUser = 0;
            wxpubUserOld.setBalance(newBalance_oldUser);
            wxpubUserOld.setIntegral(newIntegral_oldUser);
            wxpubUserOld.setUpdateTime(now);
            int i = wxpubUserMapper.updateBalance(wxpubUserOld);

            if (i == 1) {
                //增加旧会员账号出账明细
                UserAccDetail wechatUserAccDetail_oldUser = new UserAccDetail();
                wechatUserAccDetail_oldUser.setId(IdWorker.getId());
                wechatUserAccDetail_oldUser.setMerId(wxpubUserOld.getMerId());
                wechatUserAccDetail_oldUser.setUserId(wxpubUserOld.getId());
                wechatUserAccDetail_oldUser.setDeviceUniqueId(wxpubUserOld.getDeviceUniqueId());
                wechatUserAccDetail_oldUser.setDeviceType(wxpubUserOld.getDeviceType());
                wechatUserAccDetail_oldUser.setChangeInte(oldIntegral_oldUser);
                wechatUserAccDetail_oldUser.setChangeBal(oldBalance_oldUser);
                wechatUserAccDetail_oldUser.setNewBal(newBalance_oldUser);
                wechatUserAccDetail_oldUser.setNewInte(newIntegral_oldUser);
                wechatUserAccDetail_oldUser.setType(AccDetailTypeEnum.MERGE_SUB.getValue());
                wechatUserAccDetail_oldUser.setTradeno(IdWorker.getIdStr());
                wechatUserAccDetail_oldUser.setRemark(null);
                wechatUserAccDetail_oldUser.setCreateTime(now);
                wechatUserAccDetail_oldUser.setUpdateTime(now);
                int insert = userAccDetailMapper.insert(wechatUserAccDetail_oldUser);
                if (insert != 1) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
                }
            } else {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
            }

            //新会员
            WxpubUser wxpubUserNew = wxpubUserMapper.selectById(userNew.getId(), userNew.getMerId());
            if (wxpubUserNew == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该公众号微信新用户不存在");
            }

            //修改微信id
            //wechatUserNew.setWxid(wxid_userOld);
            //修改用户业务终端唯一id
            //wechatUserNew.setBizUserId(wxid_userOld);
            //计算用户余额并修改
            Double oldBalance_newUser = wxpubUserNew.getBalance();
            Integer oldIntegral_newUser = wxpubUserNew.getIntegral();
            //修改余额
            Double newBalance_newUser = Math.add(oldBalance_newUser, oldBalance_oldUser);
            Integer newIntegral_newUser = oldIntegral_newUser + oldIntegral_oldUser;
            wxpubUserNew.setBalance(newBalance_newUser);
            wxpubUserNew.setIntegral(newIntegral_newUser);
            wxpubUserNew.setUpdateTime(now);
            int j = wxpubUserMapper.updateBalance(wxpubUserNew);
            if (j == 1) {
                //增加新会员账号入账明细
                UserAccDetail wechatUserAccDetail_newUser = new UserAccDetail();
                wechatUserAccDetail_newUser.setId(IdWorker.getId());
                wechatUserAccDetail_newUser.setMerId(wxpubUserNew.getMerId());
                wechatUserAccDetail_newUser.setUserId(wxpubUserNew.getId());
                wechatUserAccDetail_newUser.setDeviceUniqueId(wxpubUserNew.getDeviceUniqueId());
                wechatUserAccDetail_newUser.setDeviceType(wxpubUserNew.getDeviceType());
                wechatUserAccDetail_newUser.setChangeInte(oldIntegral_oldUser);
                wechatUserAccDetail_newUser.setChangeBal(oldBalance_oldUser);
                wechatUserAccDetail_newUser.setNewBal(newBalance_newUser);
                wechatUserAccDetail_newUser.setNewInte(newIntegral_newUser);
                wechatUserAccDetail_newUser.setType(AccDetailTypeEnum.MERGE_ADD.getValue());
                wechatUserAccDetail_newUser.setTradeno(IdWorker.getIdStr());
                wechatUserAccDetail_newUser.setRemark(null);
                wechatUserAccDetail_newUser.setCreateTime(now);
                wechatUserAccDetail_newUser.setUpdateTime(now);
                int insert = userAccDetailMapper.insert(wechatUserAccDetail_newUser);
                if (insert != 1) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
                }
            } else {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
            }
        } else {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "目前只支持个人微信、企业微信和公众号会员合并");
        }

        //增加运营商报表改变记录
        //查询提现记录报表记录存不存在，存在则不添加
        MerReportChange merReportChange = merReportChangeMapper.selectByMerIdAndType(userDataMergeDto.getMerId(), 1);
        if(merReportChange == null){
            merReportChange = new MerReportChange();
            merReportChange.setId(IdWorker.getId());
            merReportChange.setMerId(IdWorker.getId());
            merReportChange.setType(1);
            merReportChange.setRemark("数据处理-订单清理");
            merReportChange.setCreateTime(now);
            merReportChange.setUpdateTime(now);
            merReportChangeMapper.insert(merReportChange);
        }

    }

    /**
     * 机器人数据迁移
     *
     * @param deviceDataTranferDto
     * @return
     */
    @Transactional
    @Override
    @Async("taskExecutor")
    public void deviceDateTransfer(DeviceDataTranferDto deviceDataTranferDto) {
        Long merId = deviceDataTranferDto.getMerId();
        Long deviceUniqueIdOld = deviceDataTranferDto.getDeviceUniqueIdOld();
        Long deviceUniqueIdNew = deviceDataTranferDto.getDeviceUniqueIdNew();

        if (deviceUniqueIdOld.longValue() == deviceUniqueIdNew.longValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "旧机器人和新机器人不能是同一个");
        }

        DeviceWechatInfo deviceWechatInfoNew = deviceWechatInfoMapper.selectById(deviceUniqueIdNew, merId);
        if (deviceWechatInfoNew == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人不存在");
        }

        ConfigPlan configPlan_new = configPlanMapper.selectById(deviceWechatInfoNew.getConfigId(), merId);
        if (configPlan_new == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人配置方案不存在");
        }

        Long userTypeGroupId = configPlan_new.getUserTypeGroupId();
        if (userTypeGroupId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人配置方案未配置会员类型组信息");
        }

        //买家会员类型
        UserType userType_buyer = userTypeMapper.selectDefault(merId, userTypeGroupId, IdentityEnum.BUYER.getId());
        if (userType_buyer == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人配置方案配置会员类型组未包含默认的买家身份会员类型");
        }
        //代理会员类型
        UserType userType_agent = userTypeMapper.selectDefault(merId, userTypeGroupId, IdentityEnum.AGENT.getId());
        if (userType_agent == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人配置方案配置会员类型组未包含默认的代理身份会员类型");
        }
        //合伙人会员类型
        UserType userType_partner = userTypeMapper.selectDefault(merId, userTypeGroupId, IdentityEnum.PARTNER.getId());
        if (userType_partner == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人配置方案配置会员类型组未包含默认的合伙人身份会员类型");
        }

        //1-转移会员
        //转移买家会员
        wechatUserMapper.batchUpdateDeviceInfoByIdentity(deviceUniqueIdOld, IdentityEnum.BUYER.getId(), deviceUniqueIdNew, userType_buyer.getId(), merId);
        //转移代理会员
        wechatUserMapper.batchUpdateDeviceInfoByIdentity(deviceUniqueIdOld, IdentityEnum.AGENT.getId(), deviceUniqueIdNew, userType_agent.getId(), merId);
        //转移合伙人会员
        wechatUserMapper.batchUpdateDeviceInfoByIdentity(deviceUniqueIdOld, IdentityEnum.PARTNER.getId(), deviceUniqueIdNew, userType_partner.getId(), merId);

        //2-转移订单
        //转移淘宝订单
        tbOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
        //转移京东订单
        jdOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
        //转移拼多多订单
        pddOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
        //转移唯品会订单
        vphOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
        //转移美团订单
        mtOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
        //转移抖音订单
        dyOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);

        //3-转移提现记录
        userTakeBalMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);

        //4-转移红包记录
        redPacketMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);

        //5-用户账户明细记录
        userAccDetailMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
    }

    /**
     * 会员数据-清理标签
     *
     * @param userTagsHanderDto
     * @return
     */
    @Override
    @Transactional
    public void userTagsHander(UserTagsHanderDto userTagsHanderDto) {

        Long merId = userTagsHanderDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if (merchant == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //如果输入的验证码不是系统通用密码，则需要验证
        if (!uzaiConsoleSysConfig.getDefaultPassword().equals(userTagsHanderDto.getCode())) {
            //获取存在redis中的验证码
            String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.USER_DATA_HANDER.getDesc(), merchant.getMobile()));
            //判断验证码是否过期
            if (StringUtils.isBlank(codeByRedis)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
            }
            //验证码是否正确
            if (!codeByRedis.equals(userTagsHanderDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(userTagsHanderDto.getCode())) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
            }
            //验证成功，删除验证码
            redisTemplate.delete(String.format(SmsType.USER_DATA_HANDER.getDesc(), merchant.getMobile()));
        }

        if (StringUtils.isBlank(userTagsHanderDto.getDeviceType())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择设备类型");
        }
        List<String> userIdList = userTagsHanderDto.getUserIdList();
        if (userIdList == null || userIdList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入会员id/微信id");
        }

        List<String> newTagList = userTagsHanderDto.getNewTagList();
        if (userTagsHanderDto.getTagType() != 0) { //不是清空标签
            if (newTagList == null || newTagList.size() == 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入新的标签");
            }
        }

        //修改用户余额和微信id
        if (userTagsHanderDto.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())) { //个人微信用户
            for (String userId : userIdList) {
                //会员信息
                WechatUser wechatUser = null;
                //判断是否是会员id,如果是，则先根据会员id查询
                boolean flag = StringUtils.isNumeric(userId);
                if (flag) {
                    Long id = Long.valueOf(userId);
                    wechatUser = wechatUserMapper.selectById(id, merId);
                } else {
                    wechatUser = wechatUserMapper.selectByBizUserId(userId, merId);
                }
                if (wechatUser != null) {
                    //获取会员旧标签
                    List<String> oldTagList = JSONObject.parseArray(wechatUser.getTags(), String.class);
                    if (oldTagList == null) {
                        oldTagList = new ArrayList<>();
                    }
                    if (userTagsHanderDto.getTagType() == 0) { //清空标签
                        wechatUser.setTags("");
                    } else if (userTagsHanderDto.getTagType() == 1) {//追加输入标签
                        oldTagList.addAll(newTagList);
                        //通过Java8的stream流实现去重
                        List<String> newList = oldTagList.stream().distinct().collect(Collectors.toList());
                        wechatUser.setTags(Tools.getStrEmpty(JSONObject.toJSONString(newList)));
                    } else if (userTagsHanderDto.getTagType() == 2) {//修改成输入标签
                        wechatUser.setTags(Tools.getStrEmpty(JSONObject.toJSONString(newTagList)));
                    } else if (userTagsHanderDto.getTagType() == 3) {//删除输入标签
                        oldTagList.removeAll(newTagList);
                        wechatUser.setTags(Tools.getStrEmpty(JSONObject.toJSONString(oldTagList)));
                    }
                    wechatUserMapper.updateRemarkAndTags(wechatUser);
                }
            }
        } else if (userTagsHanderDto.getDeviceType().equals(DeviceTypeEnum.DT_WORK_WECHAT.getKey())) { //企业微信
            for (String userId : userIdList) {
                //会员信息
                WxworkUser wxworkUser = null;
                //判断是否是会员id,如果是，则先根据会员id查询
                boolean flag = StringUtils.isNumeric(userId);
                if (flag) {
                    Long id = Long.valueOf(userId);
                    wxworkUser = wxworkUserMapper.selectById(id, merId);
                } else {
                    wxworkUser = wxworkUserMapper.selectByBizUserId(userId, merId);
                }
                if (wxworkUser != null) {
                    //获取会员旧标签
                    List<String> oldTagList = JSONObject.parseArray(wxworkUser.getTags(), String.class);
                    if (oldTagList == null) {
                        oldTagList = new ArrayList<>();
                    }
                    if (userTagsHanderDto.getTagType() == 0) { //清空标签
                        wxworkUser.setTags("");
                    } else if (userTagsHanderDto.getTagType() == 1) {//追加输入标签
                        oldTagList.addAll(newTagList);
                        //通过Java8的stream流实现去重
                        List<String> newList = oldTagList.stream().distinct().collect(Collectors.toList());
                        wxworkUser.setTags(Tools.getStrEmpty(JSONObject.toJSONString(newList)));
                    } else if (userTagsHanderDto.getTagType() == 2) {//修改成输入标签
                        wxworkUser.setTags(Tools.getStrEmpty(JSONObject.toJSONString(newTagList)));
                    } else if (userTagsHanderDto.getTagType() == 3) {//删除输入标签
                        oldTagList.removeAll(newTagList);
                        wxworkUser.setTags(Tools.getStrEmpty(JSONObject.toJSONString(oldTagList)));
                    }
                    wxworkUserMapper.updateRemarkAndTags(wxworkUser);
                }
            }
        } else if (userTagsHanderDto.getDeviceType().equals(DeviceTypeEnum.WX_PUB.getKey())) {//公众号用户
            for (String userId : userIdList) {
                //会员信息
                WxpubUser wxpubUser = null;
                //判断是否是会员id,如果是，则先根据会员id查询
                boolean flag = StringUtils.isNumeric(userId);
                if (flag) {
                    Long id = Long.valueOf(userId);
                    wxpubUser = wxpubUserMapper.selectById(id, merId);
                } else {
                    wxpubUser = wxpubUserMapper.selectByBizUserId(userId, merId);
                }
                if (wxpubUser != null) {
                    //获取会员旧标签
                    List<String> oldTagList = JSONObject.parseArray(wxpubUser.getTags(), String.class);
                    if (oldTagList == null) {
                        oldTagList = new ArrayList<>();
                    }
                    if (userTagsHanderDto.getTagType() == 0) { //清空标签
                        wxpubUser.setTags("");
                    } else if (userTagsHanderDto.getTagType() == 1) {//追加输入标签
                        oldTagList.addAll(newTagList);
                        //通过Java8的stream流实现去重
                        List<String> newList = oldTagList.stream().distinct().collect(Collectors.toList());
                        wxpubUser.setTags(Tools.getStrEmpty(JSONObject.toJSONString(newList)));
                    } else if (userTagsHanderDto.getTagType() == 2) {//修改成输入标签
                        wxpubUser.setTags(Tools.getStrEmpty(JSONObject.toJSONString(newTagList)));
                    } else if (userTagsHanderDto.getTagType() == 3) {//删除输入标签
                        oldTagList.removeAll(newTagList);
                        wxpubUser.setTags(Tools.getStrEmpty(JSONObject.toJSONString(oldTagList)));
                    }
                    wxpubUserMapper.updateRemarkAndTags(wxpubUser);
                }
            }
        } else {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "目前只支持个人微信、企业微信和公众号会员数据处理");
        }
    }

    /**
     * 会员数据-清理余额
     *
     * @param userBalanceHanderDto
     * @return
     */
    @Override
    @Transactional
    public void userBalanceHander(UserBalanceHanderDto userBalanceHanderDto) {

        Long merId = userBalanceHanderDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if (merchant == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //查询运营商短信验证功能信息
        boolean smsCodeFlag = true;
        MerBaseConfig merBaseConfig_smsCode = merBaseConfigMapper.selectByMerId(merchant.getId(), MerConfigKeyEnum.SMS_CODE_CONFIG.getValue());
        if (merBaseConfig_smsCode != null) {
            SmsCodeVo smsCodeVo = JSONObject.parseObject(merBaseConfig_smsCode.getVal(), SmsCodeVo.class);
            if (smsCodeVo != null && smsCodeVo.getDataHandleUserBalUpdate() == 0) { //不需要认证
                smsCodeFlag = false;
            }
        }

        if (smsCodeFlag) {
            //如果输入的验证码不是系统通用密码，则需要验证
            if (!uzaiConsoleSysConfig.getDefaultPassword().equals(userBalanceHanderDto.getCode())) {
                //获取存在redis中的验证码
                String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.USER_DATA_HANDER.getDesc(), merchant.getMobile()));
                //判断验证码是否过期
                if (StringUtils.isBlank(codeByRedis)) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                }
                //验证码是否正确
                if (!codeByRedis.equals(userBalanceHanderDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(userBalanceHanderDto.getCode())) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                }
                //验证成功，删除验证码
                redisTemplate.delete(String.format(SmsType.USER_DATA_HANDER.getDesc(), merchant.getMobile()));
            }
        }

        if (StringUtils.isBlank(userBalanceHanderDto.getDeviceType())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择设备类型");
        }
        List<String> userIdList = userBalanceHanderDto.getUserIdList();
        if (userIdList == null || userIdList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入会员id/微信id");
        }

        //修改值不能为负数
        if (Tools.getDouble(userBalanceHanderDto.getBalance()).doubleValue() < 0 || Tools.getInteger(userBalanceHanderDto.getIntegral()).intValue() < 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只能输入大于0的数");
        }

        //发送修改会员数据提醒通知
        StringBuffer content = new StringBuffer("正在修改会员余额和积分;");

        //变更余额
        Double balance = userBalanceHanderDto.getBalance();
        //修改类型类型
        Integer balanceType = userBalanceHanderDto.getBalanceType();
        Double changeBalance = 0.0D;
        //表示修改余额
        if (balance != null) {
            if (balanceType == null) { //修改余额
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入余额修改类型");
            }
            if (!Lists.newArrayList(-1, 0, 1).contains(balanceType)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "余额修改类型值有误");
            }
        }

        //表示修改积分
        Integer integral = userBalanceHanderDto.getIntegral();
        //修改积分类型
        Integer integralType = userBalanceHanderDto.getIntegralType();
        //变更积分
        Integer changeIntegral = 0;
        if (integral != null) {
            if (integralType == null) { //修改积分
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入积分修改类型");
            }
            if (!Lists.newArrayList(-1, 0, 1).contains(integralType)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "积分修改类型值有误");
            }
        }

        //当前时间
        int now = com.uzai.common.utils.DateUtil.getTime();
        //修改用户余额和微信id
        if (userBalanceHanderDto.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())) { //个人微信用户
            for (String userId : userIdList) {
                //会员信息
                WechatUser wechatUser = null;
                //判断是否是会员id,如果是，则先根据会员id查询
                boolean flag = StringUtils.isNumeric(userId);
                if (flag) {
                    Long id = Long.valueOf(userId);
                    wechatUser = wechatUserMapper.selectById(id, merId);
                } else {
                    wechatUser = wechatUserMapper.selectByBizUserId(userId, merId);
                }
                if (wechatUser != null) {

                    //修改了余额
                    if (balance != null) {
                        //旧余额
                        Double oldBalance = Tools.getDouble(wechatUser.getBalance());
                        //新余额
                        Double newBalance = 0.00D;
                        if (balanceType.intValue() == -1) { //减量
                            //减少
                            newBalance = Math.sub(oldBalance, balance);
                            changeBalance = Math.sub(0, balance);
                        } else if (balanceType.intValue() == 1) { //增量
                            //增加
                            newBalance = Math.add(oldBalance, balance);
                            changeBalance = balance;
                        } else {//修改成指定值
                            newBalance = balance;
                            changeBalance = Math.sub(newBalance, oldBalance);
                        }
                        wechatUser.setBalance(newBalance);

                        content.append("变动余额:" + changeBalance).append(";");
                    }

                    //修改了积分
                    if (integral != null) {
                        //旧积分
                        Integer oldIntegral = Tools.getInteger(wechatUser.getIntegral());
                        //新积分
                        Integer newIntegral = 0;
                        if (integralType.intValue() == -1) { //减量
                            //减少
                            newIntegral = oldIntegral - integral;
                            changeIntegral = 0 - integral;
                        } else if (integralType.intValue() == 1) { //增量
                            //增加
                            newIntegral = oldIntegral + integral;
                            changeIntegral = integral;
                        } else {//修改成指定值
                            newIntegral = integral;
                            changeIntegral = newIntegral - oldIntegral;
                        }
                        wechatUser.setIntegral(newIntegral);
                        content.append("变动积分:" + changeIntegral).append(";");
                    }

                    //修改时间
                    wechatUser.setUpdateTime(now);
                    int j = wechatUserMapper.updateBalance(wechatUser);
                    if (j == 1) {
                        //增加新会员账号入账明细
                        UserAccDetail wechatUserAccDetail = new UserAccDetail();
                        wechatUserAccDetail.setId(IdWorker.getId());
                        wechatUserAccDetail.setMerId(merId);
                        wechatUserAccDetail.setUserId(wechatUser.getId());
                        wechatUserAccDetail.setDeviceUniqueId(wechatUser.getDeviceUniqueId());
                        wechatUserAccDetail.setDeviceType(wechatUser.getDeviceType());
                        wechatUserAccDetail.setChangeInte(changeIntegral);
                        wechatUserAccDetail.setChangeBal(changeBalance);
                        wechatUserAccDetail.setNewBal(wechatUser.getBalance());
                        wechatUserAccDetail.setNewInte(wechatUser.getIntegral());
                        wechatUserAccDetail.setType(AccDetailTypeEnum.CHANGE_OPERATOR.getValue());
                        wechatUserAccDetail.setTradeno(IdWorker.getIdStr());
                        wechatUserAccDetail.setRemark(null);
                        wechatUserAccDetail.setCreateTime(now);
                        wechatUserAccDetail.setUpdateTime(now);
                        int insert = userAccDetailMapper.insert(wechatUserAccDetail);
                        if (insert != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
                        }

                        //发送异常报警通知-修改会员敏感信息
                        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                        alarmMsgFeignDto.setMerId(userBalanceHanderDto.getMerId());
                        alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER_BAL_INTE.getValue()); //修改会员余额和积分
                        //消息
                        JSONObject ext = new JSONObject();
                        //当前操作员
                        String token_key = String.format(CacheKey.LOGIN_TOKEN, userBalanceHanderDto.getLoginToken());
                        Object data = redisTemplate.opsForValue().get(token_key);
                        LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
                        if (loginVo == null) {
                            loginVo = new LoginVo();
                        }
                        ext.put("childuser", loginVo.getLoginName());
                        ext.put("content", content.toString());
                        ext.put("nick", wechatUser.getNickName());
                        ext.put("wxid", wechatUser.getBizUserId());
                        ext.put("userid", wechatUser.getId());
                        ext.put("phone", loginVo.getMobile());
                        alarmMsgFeignDto.setExt(ext.toJSONString());
//                        UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                        logger.info("---发送修改会员余额和积分报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

                        //2024-01-09修改成直接发送MQ
                        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

                    } else {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
                    }
                }
            }
        } else if (userBalanceHanderDto.getDeviceType().equals(DeviceTypeEnum.DT_WORK_WECHAT.getKey())) { //企业微信
            for (String userId : userIdList) {
                //会员信息
                WxworkUser wxworkUser = null;
                //判断是否是会员id,如果是，则先根据会员id查询
                boolean flag = StringUtils.isNumeric(userId);
                if (flag) {
                    Long id = Long.valueOf(userId);
                    wxworkUser = wxworkUserMapper.selectById(id, merId);
                } else {
                    wxworkUser = wxworkUserMapper.selectByBizUserId(userId, merId);
                }
                if (wxworkUser != null) {
                    //修改了余额
                    if (balance != null) {
                        //旧余额
                        Double oldBalance = Tools.getDouble(wxworkUser.getBalance());
                        //新余额
                        Double newBalance = 0.00D;
                        if (balanceType.intValue() == -1) { //减量
                            //减少
                            newBalance = Math.sub(oldBalance, balance);
                            changeBalance = Math.sub(0, balance);
                        } else if (balanceType.intValue() == 1) { //增量
                            //增加
                            newBalance = Math.add(oldBalance, balance);
                            changeBalance = balance;
                        } else {//修改成指定值
                            newBalance = balance;
                            changeBalance = Math.sub(newBalance, oldBalance);
                        }
                        wxworkUser.setBalance(newBalance);

                        content.append("变动余额:" + changeBalance).append(";");
                    }

                    //修改了积分
                    if (integral != null) {
                        //旧积分
                        Integer oldIntegral = Tools.getInteger(wxworkUser.getIntegral());
                        //新积分
                        Integer newIntegral = 0;
                        if (integralType.intValue() == -1) { //减量
                            //减少
                            newIntegral = oldIntegral - integral;
                            changeIntegral = 0 - integral;
                        } else if (integralType.intValue() == 1) { //增量
                            //增加
                            newIntegral = oldIntegral + integral;
                            changeIntegral = integral;
                        } else {//修改成指定值
                            newIntegral = integral;
                            changeIntegral = newIntegral - oldIntegral;
                        }
                        wxworkUser.setIntegral(newIntegral);
                        content.append("变动积分:" + changeIntegral).append(";");
                    }

                    //修改时间
                    wxworkUser.setUpdateTime(now);
                    int j = wxworkUserMapper.updateBalance(wxworkUser);
                    if (j == 1) {
                        //增加新会员账号入账明细
                        UserAccDetail wechatUserAccDetail = new UserAccDetail();
                        wechatUserAccDetail.setId(IdWorker.getId());
                        wechatUserAccDetail.setMerId(merId);
                        wechatUserAccDetail.setUserId(wxworkUser.getId());
                        wechatUserAccDetail.setDeviceUniqueId(wxworkUser.getDeviceUniqueId());
                        wechatUserAccDetail.setDeviceType(wxworkUser.getDeviceType());
                        wechatUserAccDetail.setChangeInte(changeIntegral);
                        wechatUserAccDetail.setChangeBal(changeBalance);
                        wechatUserAccDetail.setNewBal(wxworkUser.getBalance());
                        wechatUserAccDetail.setNewInte(wxworkUser.getIntegral());
                        wechatUserAccDetail.setType(AccDetailTypeEnum.CHANGE_OPERATOR.getValue());
                        wechatUserAccDetail.setTradeno(IdWorker.getIdStr());
                        wechatUserAccDetail.setRemark(null);
                        wechatUserAccDetail.setCreateTime(now);
                        wechatUserAccDetail.setUpdateTime(now);
                        int insert = userAccDetailMapper.insert(wechatUserAccDetail);
                        if (insert != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
                        }

                        //发送异常报警通知-修改会员敏感信息
                        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                        alarmMsgFeignDto.setMerId(userBalanceHanderDto.getMerId());
                        alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER_BAL_INTE.getValue()); //修改会员余额和积分
                        //消息
                        JSONObject ext = new JSONObject();
                        //当前操作员
                        String token_key = String.format(CacheKey.LOGIN_TOKEN, userBalanceHanderDto.getLoginToken());
                        Object data = redisTemplate.opsForValue().get(token_key);
                        LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
                        if (loginVo == null) {
                            loginVo = new LoginVo();
                        }
                        ext.put("childuser", loginVo.getLoginName());
                        ext.put("content", content.toString());
                        ext.put("nick", wxworkUser.getNickName());
                        ext.put("wxid", wxworkUser.getBizUserId());
                        ext.put("userid", wxworkUser.getId());
                        ext.put("phone", loginVo.getMobile());
                        alarmMsgFeignDto.setExt(ext.toJSONString());
//                        UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                        logger.info("---发送修改会员余额和积分报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

                        //2024-01-09修改成直接发送MQ
                        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

                    } else {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
                    }
                }
            }
        } else if (userBalanceHanderDto.getDeviceType().equals(DeviceTypeEnum.WX_PUB.getKey())) {//公众号用户
            for (String userId : userIdList) {
                //会员信息
                WxpubUser wxpubUser = null;
                //判断是否是会员id,如果是，则先根据会员id查询
                boolean flag = StringUtils.isNumeric(userId);
                if (flag) {
                    Long id = Long.valueOf(userId);
                    wxpubUser = wxpubUserMapper.selectById(id, merId);
                } else {
                    wxpubUser = wxpubUserMapper.selectByBizUserId(userId, merId);
                }
                if (wxpubUser != null) {

                    //修改了余额
                    if (balance != null) {
                        //旧余额
                        Double oldBalance = Tools.getDouble(wxpubUser.getBalance());
                        //新余额
                        Double newBalance = 0.00D;
                        if (balanceType.intValue() == -1) { //减量
                            //减少
                            newBalance = Math.sub(oldBalance, balance);
                            changeBalance = Math.sub(0, balance);
                        } else if (balanceType.intValue() == 1) { //增量
                            //增加
                            newBalance = Math.add(oldBalance, balance);
                            changeBalance = balance;
                        } else {//修改成指定值
                            newBalance = balance;
                            changeBalance = Math.sub(newBalance, oldBalance);
                        }
                        wxpubUser.setBalance(newBalance);

                        content.append("变动余额:" + changeBalance).append(";");
                    }

                    //修改了积分
                    if (integral != null) {
                        //旧积分
                        Integer oldIntegral = Tools.getInteger(wxpubUser.getIntegral());
                        //新积分
                        Integer newIntegral = 0;
                        if (integralType.intValue() == -1) { //减量
                            //减少
                            newIntegral = oldIntegral - integral;
                            changeIntegral = 0 - integral;
                        } else if (integralType.intValue() == 1) { //增量
                            //增加
                            newIntegral = oldIntegral + integral;
                            changeIntegral = integral;
                        } else {//修改成指定值
                            newIntegral = integral;
                            changeIntegral = newIntegral - oldIntegral;
                        }
                        wxpubUser.setIntegral(newIntegral);
                        content.append("变动积分:" + changeIntegral).append(";");
                    }

                    //修改时间
                    wxpubUser.setUpdateTime(now);
                    int j = wxpubUserMapper.updateBalance(wxpubUser);
                    if (j == 1) {
                        //增加新会员账号入账明细
                        UserAccDetail wechatUserAccDetail = new UserAccDetail();
                        wechatUserAccDetail.setId(IdWorker.getId());
                        wechatUserAccDetail.setMerId(merId);
                        wechatUserAccDetail.setUserId(wxpubUser.getId());
                        wechatUserAccDetail.setDeviceUniqueId(wxpubUser.getDeviceUniqueId());
                        wechatUserAccDetail.setDeviceType(wxpubUser.getDeviceType());
                        wechatUserAccDetail.setChangeInte(changeIntegral);
                        wechatUserAccDetail.setChangeBal(changeBalance);
                        wechatUserAccDetail.setNewBal(wxpubUser.getBalance());
                        wechatUserAccDetail.setNewInte(wxpubUser.getIntegral());
                        wechatUserAccDetail.setType(AccDetailTypeEnum.CHANGE_OPERATOR.getValue());
                        wechatUserAccDetail.setTradeno(IdWorker.getIdStr());
                        wechatUserAccDetail.setRemark(null);
                        wechatUserAccDetail.setCreateTime(now);
                        wechatUserAccDetail.setUpdateTime(now);
                        int insert = userAccDetailMapper.insert(wechatUserAccDetail);
                        if (insert != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
                        }

                        //发送异常报警通知-修改会员敏感信息
                        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                        alarmMsgFeignDto.setMerId(userBalanceHanderDto.getMerId());
                        alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER_BAL_INTE.getValue()); //修改会员余额和积分
                        //消息
                        JSONObject ext = new JSONObject();
                        //当前操作员
                        String token_key = String.format(CacheKey.LOGIN_TOKEN, userBalanceHanderDto.getLoginToken());
                        Object data = redisTemplate.opsForValue().get(token_key);
                        LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
                        if (loginVo == null) {
                            loginVo = new LoginVo();
                        }
                        ext.put("childuser", loginVo.getLoginName());
                        ext.put("content", content.toString());
                        ext.put("nick", wxpubUser.getNickName());
                        ext.put("wxid", wxpubUser.getBizUserId());
                        ext.put("userid", wxpubUser.getId());
                        ext.put("phone", loginVo.getMobile());
                        alarmMsgFeignDto.setExt(ext.toJSONString());
//                        UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                        logger.info("---发送修改会员余额和积分报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

                        //2024-01-09修改成直接发送MQ
                        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

                    } else {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
                    }
                }
            }
        } else {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "目前只支持个人微信、企业微信和公众号会员数据处理");
        }
    }

    /**
     * 历史订单处理
     *
     * @param historyOrderHanderDto
     * @return
     */
    public void orderClean(HistoryOrderHanderDto historyOrderHanderDto) {

        //验证码为空
        if (StringUtils.isBlank(historyOrderHanderDto.getCode())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入验证码");
        }

        Long merId = historyOrderHanderDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if (merchant == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        String val = (String) redisTemplate.opsForValue().get(String.format(CacheKey.DATA_HANDER_ORDER_CHEAN, merId));
        if (StringUtils.isNotBlank(val)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "30分钟只允许一次处理请求");
        }

        //如果输入的验证码不是系统通用密码，则需要验证
        if (!uzaiConsoleSysConfig.getDefaultPassword().equals(historyOrderHanderDto.getCode())) {
            //获取存在redis中的验证码
            String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.ORDER_DATA_DELETE.getDesc(), merchant.getMobile()));
            //判断验证码是否过期
            if (StringUtils.isBlank(codeByRedis)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
            }
            //验证码是否正确
            if (!codeByRedis.equals(historyOrderHanderDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(historyOrderHanderDto.getCode())) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
            }
            //验证成功，删除验证码
            redisTemplate.delete(String.format(SmsType.ORDER_DATA_DELETE.getDesc(), merchant.getMobile()));
        }

        //平台不能为空
        if (Strings.isBlank(historyOrderHanderDto.getPlatform())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择订单平台");
        }

        //查询开始时间为空
        Integer queryStartTime = historyOrderHanderDto.getQueryStartTime();
        if (queryStartTime == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入查询开始时间");
        }

        //查询结束时间为空
        Integer queryEndTime = historyOrderHanderDto.getQueryEndTime();
        if (queryEndTime == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入查询结束时间");
        }

        //判断开始时间和结束时间是否在同一月
        if (!com.uzai.console.common.utils.DateUtil.isSameMonth(new Date(queryStartTime * 1000L), new Date(queryEndTime * 1000L))) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询开始时间和结束时间不能跨月");
        }

        //发送异常消息报警
        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
        alarmMsgFeignDto.setMerId(merchant.getId());
        alarmMsgFeignDto.setType(SysMsgTypeEnum.OTHER_EXCEPTION.getValue()); //其他异常提醒
        //消息
        JSONObject ext = new JSONObject();
        StringBuilder content = new StringBuilder();
        content.append("正在删除数据库订单，删除不可恢复。来自运营商：").append(merchant.getMobile());
        //当前操作员
        ext.put("content", content.toString());
        ext.put("phone", merchant.getMobile());
        ext.put("errorcode", content.toString());
        alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---淘宝添加联盟授权，发送其他异常消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

        //2024-01-09修改成直接发送MQ
        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);


        //淘宝订单
        if (historyOrderHanderDto.getPlatform().equals(PlatformTypeEnum.TB_KEY)) {
            //删除3个月之内的
            TbOrderQuery tbOrderQuery = new TbOrderQuery();
            BeanUtils.copyProperties(historyOrderHanderDto, tbOrderQuery);
            tbOrderQuery.setMerId(merId);
            tbOrderQuery.setQueryStartTime(queryStartTime);
            tbOrderQuery.setQueryEndTime(queryEndTime);
            tbOrderQuery.setUserId(historyOrderHanderDto.getUserId());
            tbOrderMapper.deleteByParam(tbOrderQuery);
            //删除历史数据
            HistoryTbOrderOptDto historyTbOrderOptDto = new HistoryTbOrderOptDto();
            BeanUtils.copyProperties(historyOrderHanderDto, historyTbOrderOptDto);
            historyTbOrderOptDto.setMerId(merId);
            historyTbOrderOptDto.setQueryStartTime(queryStartTime);
            historyTbOrderOptDto.setQueryEndTime(queryEndTime);
            historyTbOrderOptDto.setUserId(historyOrderHanderDto.getUserId());
            String tableSuffix = DateTime.of(queryEndTime * 1000L).toString("yyMM");
            UzaiRespVo<Boolean> uzaiRespVo = historyDataFeignService.deleteByParam(tableSuffix, historyTbOrderOptDto);
            logger.info("删除淘宝历史订单，tableSuffix={}, para={},result={}", tableSuffix, JSONObject.toJSONString(historyTbOrderOptDto), JSONObject.toJSONString(uzaiRespVo));
        } else if (historyOrderHanderDto.getPlatform().equals(PlatformTypeEnum.JD_KEY)) {
            JdOrderQuery jdOrderQuery = new JdOrderQuery();
            BeanUtils.copyProperties(historyOrderHanderDto, jdOrderQuery);
            jdOrderQuery.setMerId(merId);
            jdOrderQuery.setQueryStartTime(queryStartTime);
            jdOrderQuery.setQueryEndTime(queryEndTime);
            jdOrderQuery.setUserId(historyOrderHanderDto.getUserId());
            jdOrderMapper.deleteByParam(jdOrderQuery);
        } else if (historyOrderHanderDto.getPlatform().equals(PlatformTypeEnum.PDD_KEY)) {
            PddOrderQuery pddOrderQuery = new PddOrderQuery();
            BeanUtils.copyProperties(historyOrderHanderDto, pddOrderQuery);
            pddOrderQuery.setMerId(merId);
            pddOrderQuery.setQueryStartTime(queryStartTime);
            pddOrderQuery.setQueryEndTime(queryEndTime);
            pddOrderQuery.setUserId(historyOrderHanderDto.getUserId());
            pddOrderMapper.deleteByParam(pddOrderQuery);
        } else if (historyOrderHanderDto.getPlatform().equals(PlatformTypeEnum.VPH_KEY)) {
            VphOrderQuery vphOrderQuery = new VphOrderQuery();
            BeanUtils.copyProperties(historyOrderHanderDto, vphOrderQuery);
            vphOrderQuery.setMerId(merId);
            vphOrderQuery.setQueryStartTime(queryStartTime);
            vphOrderQuery.setQueryEndTime(queryEndTime);
            vphOrderQuery.setUserId(historyOrderHanderDto.getUserId());
            vphOrderMapper.deleteByParam(vphOrderQuery);
        } else if (historyOrderHanderDto.getPlatform().equals(PlatformTypeEnum.MT_KEY)) {
            MtOrderQuery mtOrderQuery = new MtOrderQuery();
            BeanUtils.copyProperties(historyOrderHanderDto, mtOrderQuery);
            mtOrderQuery.setMerId(merId);
            mtOrderQuery.setQueryStartTime(queryStartTime);
            mtOrderQuery.setQueryEndTime(queryEndTime);
            mtOrderQuery.setUserId(historyOrderHanderDto.getUserId());
            mtOrderMapper.deleteByParam(mtOrderQuery);
        } else if (historyOrderHanderDto.getPlatform().equals(PlatformTypeEnum.ELM_KEY)) {
            ElmOrderQuery elmOrderQuery = new ElmOrderQuery();
            BeanUtils.copyProperties(historyOrderHanderDto, elmOrderQuery);
            elmOrderQuery.setMerId(merId);
            elmOrderQuery.setQueryStartTime(queryStartTime);
            elmOrderQuery.setQueryEndTime(queryEndTime);
            elmOrderQuery.setUserId(historyOrderHanderDto.getUserId());
            elmOrderMapper.deleteByParam(elmOrderQuery);
        } else if (historyOrderHanderDto.getPlatform().equals(PlatformTypeEnum.DY_KEY)) {
            DyOrderQuery dyOrderQuery = new DyOrderQuery();
            BeanUtils.copyProperties(historyOrderHanderDto, dyOrderQuery);
            dyOrderQuery.setMerId(merId);
            dyOrderQuery.setQueryStartTime(queryStartTime);
            dyOrderQuery.setQueryEndTime(queryEndTime);
            dyOrderQuery.setUserId(historyOrderHanderDto.getUserId());
            dyOrderMapper.deleteByParam(dyOrderQuery);
        } else if (historyOrderHanderDto.getPlatform().equals(PlatformTypeEnum.KS_KEY)) {
            KsOrderQuery ksOrderQuery = new KsOrderQuery();
            BeanUtils.copyProperties(historyOrderHanderDto, ksOrderQuery);
            ksOrderQuery.setMerId(merId);
            ksOrderQuery.setQueryStartTime(queryStartTime);
            ksOrderQuery.setQueryEndTime(queryEndTime);
            ksOrderQuery.setUserId(historyOrderHanderDto.getUserId());
            ksOrderMapper.deleteByParam(ksOrderQuery);
        }

        //往reids插入本次下载，允许30分钟处理一次，避免频繁提交
        redisTemplate.opsForValue().set(String.format(CacheKey.DATA_HANDER_ORDER_CHEAN, merId), merId + "", 30, TimeUnit.MINUTES);

        //增加运营商报表改变记录
        //查询提现记录报表记录存不存在，存在则不添加
        MerReportChange merReportChange = merReportChangeMapper.selectByMerIdAndType(historyOrderHanderDto.getMerId(), 1);
        if(merReportChange == null){
            int now = com.uzai.console.common.utils.DateUtil.getNowTime();
            merReportChange = new MerReportChange();
            merReportChange.setId(IdWorker.getId());
            merReportChange.setMerId(IdWorker.getId());
            merReportChange.setType(1);
            merReportChange.setRemark("数据处理-订单清理");
            merReportChange.setCreateTime(now);
            merReportChange.setUpdateTime(now);
            merReportChangeMapper.insert(merReportChange);
        }

    }
}
